10. 解决方案:For 循环
练习解决方案:创建用户名
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for name in names:
usernames.append(name.lower().replace(" ", "_"))
print(usernames)
输出:
['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']
练习解决方案:使用 Range 修改用户名
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
for i in range(len(usernames)):
usernames[i] = usernames[i].lower().replace(" ", "_")
print(usernames)
输出:
['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']
练习解决方案:标记计数器
你可以使用字符串索引判断每个令牌是否以尖括号开始和结束。
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
for token in tokens:
if token[0] == '<' and token[-1] == '>':
count += 1
print(count)
输出:
2
练习解决方案:创建 HTML 列表
items = ['first string', 'second string']
html_str = "<ul>\n"
for item in items:
html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"
print(html_str)
输出:
<ul>
<li>first string</li>
<li>second string</li>
</ul>